#include "CAppendTable.h"
#include "CTableConfigure.h"
#include "CLogRecord.h"
#include "CppSQLite3.h"
#include <sstream>
#include <iostream>
#include <algorithm>

void CAppendTable::setTableConfigure(const CTableConfigurePtr& tableConfigure)
{
	CTableBase::setTableConfigure(tableConfigure);
}

int CAppendTable::writeRecord(CLogRecordPtr logRecord)
{
	try {
		// Check if we have the required components
		if (!logRecord || !m_tableConfigure || !m_logDatabase) {
			return -1; // Error: missing record, configuration, or database
		}
		
		// Get the database connection
		CppSQLite3DB* db = m_logDatabase->getDatabaseConnection();
		if (!db) {
			return -2; // Error: no database connection
		}
		
		// Get the table name
		std::string tableName = m_tableConfigure->getTableName();
		if (tableName.empty()) {
			return -3; // Error: no table name
		}
		
		// Get the record fields
		auto& recordFields = logRecord->GetFields();
		
		// Validate fields against table schema
		std::vector<std::string> missingFields;
		std::vector<std::string> extraFields;
		
		// Check for missing fields (fields in table but not in record)
		for (const auto& tableField : m_tableFields) {
			std::string fieldName = tableField.first;
			if (fieldName == "id")
				continue;
			
			if (recordFields.find(fieldName) == recordFields.end()) {
				missingFields.push_back(fieldName);
			}
		}
		
		// Check for extra fields (fields in record but not in table)
		for (const auto& recordField : recordFields) {
			std::string fieldName = recordField.first;
			bool found = false;
			for (const auto& tableField : m_tableFields) {
				if (tableField.first == fieldName) {
					found = true;
					break;
				}
			}
			if (!found) {
				extraFields.push_back(fieldName);
			}
		}
		
		// Print missing fields for debugging
		if (!missingFields.empty()) {
			std::cout << "Warning: Missing fields in record for table '" << tableName << "': ";
			for (size_t i = 0; i < missingFields.size(); ++i) {
				if (i > 0) std::cout << ", ";
				std::cout << missingFields[i];
			}
			std::cout << std::endl;
		}
		
		// Print extra fields for debugging
		if (!extraFields.empty()) {
			std::cout << "Warning: Extra fields in record for table '" << tableName << "': ";
			for (size_t i = 0; i < extraFields.size(); ++i) {
				if (i > 0) std::cout << ", ";
				std::cout << extraFields[i];
			}
			std::cout << std::endl;
		}
		
		// Use base class InsertRecord method
		return InsertRecord(logRecord);
		
	} catch (const CppSQLite3Exception& e) {
		// Handle SQLite exceptions
		//std::cout << "SQLite error in writeRecord: " << e.errorMessage() << std::endl;
		return -4; // Error: SQLite exception
	} catch (const std::exception& e) {
		// Handle other exceptions
		std::cout << "General error in writeRecord: " << e.what() << std::endl;
		return -5; // Error: general exception
	}
}


int CAppendTable::getTableType() const
{
	return TableTypeAppend;
}




